package net.maku.system.erp.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.AllArgsConstructor;
import net.maku.framework.common.constant.Constant;
import net.maku.framework.common.utils.PageResult;
import net.maku.framework.mybatis.service.impl.BaseServiceImpl;
import net.maku.system.erp.convert.SysWarehouseConvert;
import net.maku.system.erp.dao.SysWarehouseDao;
import net.maku.system.erp.entity.SysWarehouseEntity;
import net.maku.system.erp.query.SysWarehouseQuery;
import net.maku.system.erp.service.SysWarehouseService;
import net.maku.system.erp.vo.SysWarehouseVO;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 机构管理
 *
 * @author 阿沐 babamu@126.com
 * <a href="https://maku.net">MAKU</a>
 */
@Service
@AllArgsConstructor
public class SysWarehouseServiceImpl extends BaseServiceImpl<SysWarehouseDao, SysWarehouseEntity> implements SysWarehouseService {


    @Override
    public PageResult<SysWarehouseVO> page(SysWarehouseQuery query) {
        // 查询参数
        Map<String, Object> params = getParams(query);

        // 分页查询
        IPage<SysWarehouseEntity> page = getPage(query);
        params.put(Constant.PAGE, page);

        // 数据列表
        List<SysWarehouseEntity> list = baseMapper.getList(params);
        List<SysWarehouseVO> respData = SysWarehouseConvert.INSTANCE.convertList(list);
        return new PageResult<>(respData, page.getTotal());
    }

    private Map<String, Object> getParams(SysWarehouseQuery query) {
        Map<String, Object> params = new HashMap<>();
        params.put("name", query.getName());
        params.put("address", query.getAddress());
        params.put("warehouseCode", query.getWarehouseCode());
        params.put("comment", query.getComment());

        // 数据权限
        params.put(Constant.DATA_SCOPE, getDataScope("t1", null));

        return params;
    }

    @Override
    public List<SysWarehouseVO> getList() {
        Map<String, Object> params = new HashMap<>();

        // 数据权限
        params.put(Constant.DATA_SCOPE, getDataScope("t1", "id"));

        // 机构列表
        List<SysWarehouseEntity> entityList = baseMapper.getList(params);

        return SysWarehouseConvert.INSTANCE.convertList(entityList);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(SysWarehouseVO vo) {
        SysWarehouseEntity entity = SysWarehouseConvert.INSTANCE.convert(vo);
        baseMapper.insert(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(SysWarehouseVO vo) {
        SysWarehouseEntity entity = SysWarehouseConvert.INSTANCE.convert(vo);
        updateById(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Long id) {
        // 删除
        removeById(id);
    }

}
